import React from 'react'
import { Breadcrumb, Icon, Input, Button, Table, Modal, Pagination, Form, message, Row, Col } from 'antd'
import moment from 'moment'
import { hashHistory } from 'react-router'
import $ from 'jquery'
import Config from '../../common/config'
import server from '../server'

const config = new Config()
const FormItem = Form.Item
const token = sessionStorage.getItem('token')
let UserInfo = sessionStorage.getItem('UserInfo')
UserInfo = UserInfo ? JSON.parse(UserInfo) : {}
const root = UserInfo.root
const auth = root ? {} : (UserInfo.auth ? (UserInfo.auth[server.serverName] || {}) : {})

class UserForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      newPassword: null,//新用户密码
      reNewPassword: null,//新用户密码确认
      visible: false,//用户详情模态框
      resetPassword: false,//重置密码模态框
      userList: [],//用户列表
      detail: { user_msgs: [] },//用户详情
      page: 1,//当前页码
      count: 0,//总人数
    }
  }
  componentDidMount() {
    if (root || auth['/user/list']) {
      this.getUsers().then(res => {
        console.log(res)
        if (res.code == 200) {
          this.setState({
            userList: res.userList || [],
            count: res.count
          })
        } else {
          message.info('服务器繁忙')
        }
      }).catch(err => {
        console.log(err)
        message.info('发生错误')
      })
    } else {
      message.info('无权限')
    }

  }
  //获取管理员列表
  getUsers(data) {
    return Promise.resolve(
      $.ajax({
        url: `${config.Priviliege}/user/list`,
        type: "get",
        async: true,
        headers: { Authorization: 'Bearer ' + token },
        data
      })
    )
  }

  //搜索
  search() {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        return this.getUsers(values).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.setState({
              userList: res.userList || [],
              count: res.count,
              page: 1
            })
          } else {
            message.info('服务器繁忙')
          }
        }).catch(err => {
          console.log(err)
          message.info('发生错误')
        })
      }
    })
  }
  //重置搜索条件
  clearSearch() {
    this.props.form.resetFields(['name', 'userName', 'departmentName', 'roleName']);
    this.search()
  }

  //删除员工
  delUser(id) {
    Modal.confirm({
      title: '删除员工',
      content: '确认删除该员工吗?',
      onCancel: () => { message.info('取消删除员工') },
      onOk: () => {
        return Promise.resolve(
          $.ajax({
            url: `${config.Priviliege}/user/delete`,
            type: "post",
            data: { userId: id },
            headers: { Authorization: 'Bearer ' + token },
          })
        ).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.search()
          } else if (res.code == 201) {
            message.info(res.msg)
          } else {
            message.info('服务器繁忙')
          }
        }).catch(err => {
          console.log(err)
          message.info('发生错误')
        })
      }
    })
  }

  //关闭详情模态框
  closeModal() {
    this.setState({
      visible: false
    })
  }

  //查看员工信息详情
  detail(text, record) {
    this.setState({
      visible: true,
      detail: record,
    })
  }

  //查看所有权限
  allAuth(text, record) {
    const path = {
      pathname: '/userAllAuth',
      state: record,
    }
    hashHistory.push(path);
  }
  //确定重置密码
  resetPassword() {
    const { newPassword, reNewPassword, detail } = this.state
    if (newPassword && newPassword == reNewPassword) {
      if (!/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$/.test(newPassword)) {
        return message.error('密码不符合规则')
      }
      return Promise.resolve(
        $.ajax({
          url: `${config.Priviliege}/user/changePassword`,
          type: "post",
          headers: { Authorization: 'Bearer ' + token },
          data: {
            userId: detail.id,
            newPassword
          },
        })
      ).then(res => {
        console.log(res)
        if (res.code == 200) {
          message.info('修改成功')
          this.setState({
            resetPassword: false,
            newPassword: null,
            reNewPassword: null
          })
        } else if (res.code == 201) {
          message.info(res.msg)
        } else {
          message.info('服务器繁忙')
        }
      }).catch(err => {
        console.log(err)
        message.info('发生错误')
      })
    } else {
      message.error('两次密码不一致!')
    }
  }

  //重置密码按钮
  changePassword(text) {
    this.setState({
      resetPassword: true,
      detail: text,
    })
  }

  newPassword(e) {
    this.setState({
      newPassword: e.target.value.replace(' ', '')
    })
  }
  reNewPassword(e) {
    this.setState({
      reNewPassword: e.target.value.replace(' ', '')
    })
  }
  //切换页面
  changePage(page) {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values.page = page
        return this.getUsers(values).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.setState({
              userList: res.userList,
              count: res.count,
              page: page
            })
          } else {
            message.info('服务器繁忙')
          }
        }).catch(err => {
          console.log(err)
          message.info('发生错误')
        })
      }
    })
  }

  //编辑员工
  edit(record) {
    const path = {
      pathname: '/userEdit',
      state: record,
    }
    hashHistory.push(path);
  }

  //编辑权限
  editAuth(record) {
    const path = {
      pathname: '/userAuth',
      state: record,
    }
    hashHistory.push(path);
  }

  render() {
    const { getFieldDecorator } = this.props.form
    const record = this.state.detail
    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
        render: (text, record) => {
          let num = 100000 + record.id + ''
          return num.substring(1)
        }
      },
      {
        title: '用户名',
        dataIndex: 'userName',
      }, {
        title: '姓名',
        render: (text, record) => {
          if (record.user_msgs[0]) {
            return record.user_msgs[0].name
          }
        }
      }, {
        title: '电话号码',
        render: (text, record) => {
          if (record.user_msgs[0]) {
            return record.user_msgs[0].phone
          }
        }
      }, {
        title: '性别',
        render: (text, record) => {
          if (record.user_msgs[0]) {
            if (record.user_msgs[0].gender == 0) {
              return '女'
            } else {
              return '男'
            }
          }
        }
      }, {
        title: '用户状态',
        render: (text, record) => {
          if (record.user_msgs[0]) {
            if (record.user_msgs[0].status == 0) {
              return '离职'
            } else if (record.user_msgs[0].status == 1) {
              return '在职'
            } else if (record.user_msgs[0].status == 2) {
              return '试用期'
            }
          }
        }
      }, {
        title: '部门',
        render: (text, record) => {
          if (record.department) {
            return record.department.name
          }
        }
      }, {
        title: '角色',
        render: (text, record) => {
          if (record.roles) {
            return record.roles.map(value => {
              return value.name
            }).join(',')
          }
        }
      }, {
        title: '最后登陆时间',
        render: (text, record) => {
          return record.lastLoginDate ? moment(record.lastLoginDate).format('YYYY-MM-DD HH:mm:ss') : '从未登陆过'
        }
      }, {
        title: '操作',
        render: (text, record) => (
          <div>
            <span
              className='todoAction'
              style={{ margin: '0 10px' }}
              onClick={this.detail.bind(this, text, record)}
            >详情</span>
            {
              (root || auth['/user/update']) ?
                <span
                  className='todoAction'
                  style={{ margin: '0 10px' }}
                  onClick={this.edit.bind(this, record)}
                >更新</span>
                : ''
            }
            {(root || auth['/authority/user']) ?
              <span
                className='todoAction'
                style={{ marginLeft: 10 }}
                onClick={this.editAuth.bind(this, record)}
              >设置权限</span>
              : ''
            }
            {(root || auth['/authority/getUserAllAuth']) ?
              <span
                className='todoAction'
                style={{ marginLeft: 10 }}
                onClick={this.allAuth.bind(this, text, record)}
              >查看拥有权限</span>
              : ''
            }
            {
              (root || auth['/user/delete']) ?
                <span
                  className='todoAction'
                  style={{ margin: '0 10px' }}
                  onClick={this.delUser.bind(this, record.id)}
                >删除</span>
                : ''
            }
            {
              (root || auth['/user/changePassword']) ?
                <span
                  className='todoAction'
                  onClick={this.changePassword.bind(this, text)}
                >重置密码</span>
                : ''
            }
          </div>
        )
      }];

    return (
      <div className='goods-label'>
        <div className='goods-label-cont clearfix'>
          <div className='goods-label-cont-nav clearfix'>
            <Breadcrumb separator=">">
              <Breadcrumb.Item>权限管理</Breadcrumb.Item>
              <Breadcrumb.Item><span className='separator-a'>员工管理</span></Breadcrumb.Item>
            </Breadcrumb>
          </div>
          {/* 搜索 */}
          <Form>
            <div className='member-content-Search clearfix'>
              <FormItem className='addetd' style={{ minHeight: '40px', marginRight: "20px", width: "250px", display: "inline-block", }}>
                {getFieldDecorator('name', {
                  rules: [
                    { max: 5, message: '长度不能超过5' }
                  ],
                  initialValue: ""
                })(
                  <Input
                    className='addetd-a-r'
                    addonBefore="姓名"
                    placeholder="搜索姓名"
                    style={{ height: '40px' }}
                    onChange={(e) => { e.target.value = $.trim(e.target.value) }}
                  />
                )}
              </FormItem>
              <FormItem className='addetd' style={{ minHeight: '40px', marginRight: "20px", width: "250px", display: "inline-block", }}>
                {getFieldDecorator('userName', {
                  rules: [
                    { max: 5, message: '长度不能超过5' }
                  ],
                  initialValue: ""
                })(
                  <Input
                    className='addetd-a-r'
                    addonBefore="用户名"
                    placeholder="搜索用户名"
                    style={{ height: '40px' }}
                    onChange={(e) => { e.target.value = $.trim(e.target.value) }}
                  />
                )}
              </FormItem>
              <FormItem className='addetd' style={{ minHeight: '40px', marginRight: "20px", width: "250px", display: "inline-block", }}>
                {getFieldDecorator('departmentName', {
                  rules: [
                    { max: 10, message: '长度不能超过10' }
                  ],
                  initialValue: ""
                })(
                  <Input
                    className='addetd-a-r'
                    addonBefore="部门"
                    placeholder="搜索部门"
                    style={{ height: '40px' }}
                    onChange={(e) => { e.target.value = $.trim(e.target.value) }}
                  />
                )}
              </FormItem>
              <FormItem className='addetd' style={{ minHeight: '40px', marginRight: "20px", width: "250px", display: "inline-block", }}>
                {getFieldDecorator('roleName', {
                  rules: [
                    { max: 10, message: '长度不能超过10' }
                  ],
                  initialValue: ""
                })(
                  <Input
                    className='addetd-a-r'
                    addonBefore="角色"
                    placeholder="搜索角色"
                    style={{ height: '40px' }}
                    onChange={(e) => { e.target.value = $.trim(e.target.value) }}
                  />
                )}
              </FormItem>
              {
                (root || auth['/user/list']) ?
                  <div style={{ float: 'left', width: 220 }}>
                    <Button type="primary" className='member-button' icon="search" onClick={this.search.bind(this)}>搜索</Button>
                    <Button type="primary" className='member-button' icon="reload" onClick={this.clearSearch.bind(this)}>重置</Button>
                  </div>
                  : ""
              }
            </div>
          </Form>
          {/* 管理员列表 */}
          <div className='allgoods-table clearfix'>
            <Table
              rowKey='id'
              columns={columns}
              dataSource={this.state.userList}
              pagination={false}
              bordered
            />
            {
              (root || auth['/user/save']) ?
                <div className='goods-label-tabletr'>
                  <Button
                    className='member-button-aa'
                    type='primary'
                    onClick={() => { window.location.hash = '/userAdd' }}
                  ><Icon type="plus" />新增</Button>
                </div>
                : ''
            }
          </div>
          <div style={{ textAlign: 'center' }}>
            <Pagination
              total={this.state.count}
              showTotal={total => `共 ${total} 条记录`}
              pageSize={10}
              current={this.state.page}
              onChange={this.changePage.bind(this)}
            />
          </div>
        </div>

        {/* 用户详情 */}
        <Modal
          visible={this.state.visible}
          title={'员工详情'}
          maskClosable={false}
          onCancel={this.closeModal.bind(this)}
          footer={null}
          className='manager-modal'
          width='600px'
        >
          <div style={{ padding: '0 50px' }}>
            <Row>
              <Col span={12}>
                <span >用户名：</span>
                <span>{record.userName}</span>
              </Col>
              <Col span={12}>
                <span >姓名：</span>
                <span>{
                  record.user_msgs[0] ? record.user_msgs[0].name : ''
                }</span>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <span >电话：</span>
                <span>{
                  record.user_msgs[0] ? record.user_msgs[0].phone : ''
                }</span>
              </Col>
              <Col span={12}>
                <span >QQ：</span>
                <span>{
                  record.user_msgs[0] ? record.user_msgs[0].qq : ''
                }</span>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <span >生日：</span>
                <span>{
                  record.user_msgs[0] ? moment(record.user_msgs[0].birthday).format('YYYY-MM-DD') : ''
                }</span>
              </Col>
              <Col span={12}>
                <span >性别：</span>
                <span>{
                  function () {
                    if (record.user_msgs[0]) {
                      if (record.user_msgs[0].gender == 0) {
                        return '女'
                      } else {
                        return '男'
                      }
                    }
                  }()
                }</span>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <span >部门：</span>
                <span>{
                  record.department ? record.department.name : ''
                }</span>
              </Col>
              <Col span={12}>
                <span >角色：</span>
                <span>{
                  function () {
                    if (record.roles) {
                      return record.roles.map(value => {
                        return value.name
                      }).join(',')
                    }
                  }()
                }</span>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <span >状态：</span>
                <span>{
                  function () {
                    if (record.user_msgs[0]) {
                      if (record.user_msgs[0].status == 0) {
                        return '离职'
                      } else if (record.user_msgs[0].status == 1) {
                        return '在职'
                      } else if (record.user_msgs[0].status == 2) {
                        return '试用期'
                      }
                    }
                  }()
                }</span>
              </Col>
              <Col span={12}>
                <span >最后登录时间:</span>
                <span>{
                  record.lastLoginDate ? moment(record.lastLoginDate).format('YYYY-MM-DD hh:mm:ss') : '从未登录过'
                }</span>
              </Col>
            </Row>
            <Row>
              <Col>
                <span >备注：</span>
                <div style={{ width: '85%', wordWrap: 'break-word', display: 'inline-block' }}>{
                  record.user_msgs[0] ? record.user_msgs[0].remark : ''
                }</div>
              </Col>
            </Row>
          </div>
        </Modal>
        <Modal
          title='重置密码'
          visible={this.state.resetPassword}
          maskClosable={false}
          onOk={this.resetPassword.bind(this)}
          width='400px'
          onCancel={() => {
            this.setState({
              resetPassword: false,
              newPassword: null,
              reNewPassword: null
            })
          }}
          className='resetModal'
        >
          <div style={{ padding: 20 }}>
            <div style={{ marginBottom: 20 }}>
              <span className='resetspan'>新密码:</span>
              <Input
                type='password'
                placeholder='请输入新密码'
                style={{ width: 200 }}
                autoComplete='off'
                value={this.state.newPassword}
                onChange={this.newPassword.bind(this)}
              />
              <span className='resetspan'></span>
              <span>密码必须包含大、小写字母和数字、</span>
              <span className='resetspan'></span>
              <span>长度不小于8;</span>
            </div>
            <div>
              <span className='resetspan'>新密码确认:</span>
              <Input
                type='password'
                placeholder='请确认新密码'
                style={{ width: 200 }}
                autoComplete='off'
                value={this.state.reNewPassword}
                onChange={this.reNewPassword.bind(this)}
              />
            </div>
          </div>
        </Modal>
      </div>
    )
  }
}

const User = Form.create()(UserForm);
export default User;